package model

import (
	"errors"
	"strconv"
)

type DataSourceModel struct {
	Id       string `db:"id" from:"id" json:"id"`
	Address  string `db:"address" from:"address" json:"address"`
	Name     string `db:"name" from:"name" json:"name"`
	Port     int    `db:"port" from:"port" json:"port"`
	Username string `db:"username" from:"username" json:"username"`
	Password string `db:"password" from:"password" json:"password"`
	Type     string `db:"type" from:"type" json:"type"`
	Remark   string `db:"remark" from:"remark" json:"remark"`
	SortNum  int    `db:"sortNum" from:"sortNum" json:"sortNum"`
}

func (dataSourceModel *DataSourceModel) Insert() error {
	_, err := DB.Exec("insert into data_source(id, name, address, port, username, password, type, remark, sortNum) values(?, ?, ?, ?, ?, ?, ?, ?, ?)",
		dataSourceModel.Id, dataSourceModel.Name, dataSourceModel.Address,
		dataSourceModel.Port, dataSourceModel.Username,
		dataSourceModel.Password, dataSourceModel.Type,
		dataSourceModel.Remark, dataSourceModel.SortNum)
	if err != nil {
		return err
	}
	return nil
}

func (dataSourceModel *DataSourceModel) Update() error {
	if dataSourceModel.Id == "" {
		return errors.New("No id")
	}
	_, err := DB.Exec("update data_source set name=?, address=?, port=?, username=?, password=?, type=?, remark=?, sortNum=? where id=?",
		dataSourceModel.Name, dataSourceModel.Address,
		dataSourceModel.Port, dataSourceModel.Username,
		dataSourceModel.Password, dataSourceModel.Type,
		dataSourceModel.Remark, dataSourceModel.SortNum, dataSourceModel.Id)
	if err != nil {
		return err
	}
	return nil
}

func (dataSourceModel *DataSourceModel) Delete() error {
	var err error
	if dataSourceModel.Id != "" {
		_, err = DB.Exec("delete from data_source where id=?", dataSourceModel.Id)
	} else {
		err = errors.New("No id")
	}
	if err != nil {
		return err
	}
	return nil
}
func (dataSourceModel *DataSourceModel) List(pageNo int, pageSize int) ([]DataSourceModel, error) {
	offset := strconv.Itoa((pageNo - 1) * pageSize)
	dataSourceModels := []DataSourceModel{}
	err := DB.Select(&dataSourceModels, "select * from data_source limit "+strconv.Itoa(pageSize)+" offset "+offset)
	if err != nil {
		return dataSourceModels, err
	}
	return dataSourceModels, nil
}
